package com.example.helloworld;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;

public class NetworkUtils {

    public static String getIPAddress(Context context) {
        String ipv4 = "";
        try {
            // 获取wifi服务
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            // 判断wifi是否开启
            if (!wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(true);
            }
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            ipv4 = intToIp(ipAddress);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ipv4;
    }

    private static String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    // 获取IPv4地址
    public static String getIPv4Address() {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress() && addr instanceof java.net.Inet4Address) {
                        return addr.getHostAddress();
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
    /**
     * 获取本地主机名
     * @return 主机名
     */
    public static String getHostName() {
        try {
            // 获取本地主机地址
            InetAddress localhost = InetAddress.getLocalHost();
            // 返回主机名
            return localhost.getHostName();
        } catch (UnknownHostException e) {
            // 如果无法获取主机名，则捕获异常并返回null或者错误信息
            e.printStackTrace();
            return null;
        }
    }
}

